package com.store.app.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.bean.BitmapBean;
import com.store.app.bean.GoodsBean;
import com.store.app.http.Stores;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.stores.MultipartEntity;
import com.store.app.utils.GoToLogin;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.SettingData;
import com.store.app.utils.Utils;
import com.store.app.utils.UtilsBitmap;
import com.yalantis.ucrop.CropUtils;
import com.yalantis.ucrop.UCrop;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * 扫描商品后跳转的商品详情页面
 */
public class ScanAddGoods2Activity extends BaseActivity implements OnClickListener, IOnHttpListener {
    private EditText etName;
    private EditText etBarcode;
    private EditText etSpec;
    //private TextView etVender;
    //private TextView etBrand;
    private Spinner spinner;
    private EditText etCost;//进价
    private EditText etPrice;//售价
    private EditText etStore;
    private TextView etExpirationDate;
    private TextView etExpiration;
    private ImageView pic_img;
    private TextView mSwitch_sp_tv;
    //private TextView tvAddPicHint;
    //添加到收银页面
    private Switch mSwitch;
    //添加到网上便利店
    private Switch mSwitch_sp;
    //知否支持礼券兑换
    private Switch mSwitch_coupon;
    private String goodsCategory;


    private static final int MSG_REQUEST_SUCCESS = 0;
    private static final int MSG_REQUEST_FAILED = 1;
    private static final int MSG_GUID_SUCCESS = 2;
    private static final int MSG_IMG_SUCC = 3;
    private static final int FLAG_CHOOSE_IMG = 5;
    private static final int FLAG_CHOOSE_PHONE = 6;
    private static final int FLAG_MODIFY_FINISH = 7;
    private Handler mHandler;
    private static String localTempImageFileName = "";
    //图片地址
    private String img_add = "";
    //上传的bitmap
    private Bitmap newbitmap = null;
    private GoodsBean bean;
    private GoToLogin goToLogin;
    private NetRequest netRequest;
    private EditText et_fanli;
    private BitmapBean bitmapBean;

    private static final int CLASS_REQUEST_CODE = 2;      //获取商品分类的请求id
    private List<Map<String, String>> mDatas = new ArrayList<Map<String, String>>();
    private List<String> keyData = new ArrayList<String>();
    private List<String> valueData = new ArrayList<String>();
    private String doc_id;
    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            mHandler.sendEmptyMessage(MSG_REQUEST_SUCCESS);
        }

        if (requestId == CLASS_REQUEST_CODE) {
            //数据获取成功
            try {
                JSONObject datas = new JSONObject(result);
                Iterator it = datas.keys();
                Map<String, String> map = null;
                while (it.hasNext()) {
                    map = new HashMap<String, String>();
                    String key = (String) it.next();
                    String value = datas.getString(key);
                    map.put(key, value);
                    keyData.add(key);
                    valueData.add(value);
                    mDatas.add(map);
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.item_spinner, valueData);
//                adapter.setDropDownViewResource(R.layout.item_spinner);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinner.setAdapter(adapter);
                for (int i = 0; i < valueData.size(); i++) {
                    String string = valueData.get(i);
                    if (string.equals(bean.getCategory_id())) {
                        spinner.setSelection(i);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }else  if(requestId == 4){
            try {
                JSONObject object = new JSONObject(result);
                 doc_id = object.getString("doc_id");
                Log.v("zyl", "上传图片成功：" + doc_id);
                pic_img.setImageBitmap(bitmapBean.getBitmap());
                newbitmap = bitmapBean.getBitmap();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        if (requestId == 1) {
            Message message
                    = Message.obtain();
            message.what = MSG_REQUEST_FAILED;
            message.obj = msg;
            mHandler.sendMessage(message);
        }
    }

    private void initView() {
        et_fanli = (EditText) findViewById(R.id.et_fanli);
    }


    private class WeakHandler extends Handler {
        private final WeakReference<ScanAddGoods2Activity> mReference;

        public WeakHandler(ScanAddGoods2Activity activity) {
            mReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            ScanAddGoods2Activity activity = mReference.get();
            if (activity == null) {
                return;
            }
            activity.dismissProgressDialog();
            switch (msg.what) {
                case MSG_REQUEST_SUCCESS:
                    InputMethodManager imm = (InputMethodManager) etName.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(etName.getApplicationWindowToken(), 0);

                    }
                    activity.showToast("提交成功");
                    activity.setResult(RESULT_OK, activity.getIntent());
                    activity.finish();
                    break;
                case MSG_REQUEST_FAILED:
                    activity.showToast((String) msg.obj);
                    break;
                case MSG_GUID_SUCCESS:
                    break;
                case MSG_IMG_SUCC:
                    postdata((String) msg.obj, false);
                    break;
                default:
                    break;
            }
        }
    }


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scangoods3);
        initView();
        Log.v("zyl", "ScanAddGoods2Activity onCreate");
        ExitApplication.getInstance().addActivity(this);
//		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        mHandler = new WeakHandler(this);
        bean = (GoodsBean) getIntent().getSerializableExtra(GoodsBean.class.getSimpleName());
        Log.v("zyl", "bean:" + bean.toString());
        Log.v("zyl", "bean.getItem_id():" + bean.getItem_id());
        Log.v("zyl", "bean.getItem_code():" + bean.getItem_code());
        netRequest = new NetRequest(this);
        goToLogin = new GoToLogin(this);
        findViews();
        setListeners();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    public void doInput(View view) {
        showInputDialog((TextView) view);
    }

    private void findViews() {
        pic_img = (ImageView) findViewById(R.id.img_pic);
        //名称
              etName = (EditText) findViewById(R.id.et_name);
        String s_name = bean.getItem_name().trim();
        if (!TextUtils.isEmpty(s_name) && !s_name.equals("null")) {
            etName.setText(s_name);
            etName.setOnClickListener(null);
            etName.setEnabled(false);
        }
        //条码
        etBarcode = (EditText) findViewById(R.id.et_barcode);
        String s_barcode = bean.getBarcode().trim();
        if (!TextUtils.isEmpty(s_barcode) && !s_barcode.equals("null")) {
            etBarcode.setText(s_barcode);
            etBarcode.setOnClickListener(null);
            etBarcode.setEnabled(false);
        }
        //规格
        etSpec = (EditText) findViewById(R.id.et_spec);
        String s_spec = bean.getSpecification().trim();
        if (!TextUtils.isEmpty(s_spec) && !s_spec.equals("null")) {
            etSpec.setText(s_spec);

        }
        //分类
        spinner = (Spinner) findViewById(R.id.spinner);

        //获取商品分类数据
        netRequest.requestTypeList(CLASS_REQUEST_CODE);
        //进价
        etCost = (EditText) findViewById(R.id.et_cost);
        String s_ecost = bean.getCost_price() + "".trim();
        if (!TextUtils.isEmpty(s_ecost) && !s_ecost.equals("null")) {
            etCost.setText(s_ecost);
        }
        if (etCost.getText().toString().trim().equals("0.00")) {
            etCost.setText("");
        }
        //售价
        etPrice = (EditText) findViewById(R.id.et_price);
        String s_eprice = bean.getMarket_price() + "".trim();
        if (!TextUtils.isEmpty(s_eprice) && !s_eprice.equals("null")) {
            etPrice.setText(s_eprice);
        }
        //库存
        etStore = (EditText) findViewById(R.id.et_store);
        String s_estore = bean.getSale_qty() + "".trim();
        if (!TextUtils.isEmpty(s_estore) && !s_estore.equals("null")) {
            etStore.setText(s_estore);
            etStore.setOnClickListener(null);
            etStore.setEnabled(false);
        }
        //生产日期
        etExpirationDate = (TextView) findViewById(R.id.et_expiration_date);
        String s_expirdate = bean.getProduction_date() + "".trim();
        if (!TextUtils.isEmpty(s_expirdate) && !s_expirdate.equals("null")) {
            etExpirationDate.setText(s_expirdate);
        }
        //保质期
        etExpiration = (TextView) findViewById(R.id.et_expiration);
        String s_expir = bean.getDurability_period() + "".trim();
        Log.v("zyl", "保质期为：" + s_expir);
        if (!TextUtils.isEmpty(s_expir) && !s_expir.equals("null") && !(s_expir.equals("0"))) {
            etExpiration.setText(s_expir);
        }
        //tvAddPicHint = (TextView) findViewById(R.id.tv_add_pic_hint);

        mSwitch = (Switch) findViewById(R.id.sh);
        if ("Y".equals(bean.getIs_show())) {
            mSwitch.setChecked(true);
        } else {
            mSwitch.setChecked(false);
        }
        mSwitch_coupon = (Switch) findViewById(R.id.lq);
        if ("Y".equals(bean.getIs_exchange())) {
            mSwitch_coupon.setChecked(true);
        } else {
            mSwitch_coupon.setChecked(false);
        }
        mSwitch_sp = (Switch) findViewById(R.id.sp);
        if ("Y".equals(bean.getIs_sell())) {
            mSwitch_sp.setChecked(true);
        } else {
            mSwitch_sp.setChecked(false);
        }

        mSwitch_sp_tv = (TextView) findViewById(R.id.sp_tv);
        mSwitch_sp_tv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mSwitch_sp.isChecked()) {
                    mSwitch_sp.setChecked(false);
                } else {
                    if (isAddShopCheck()) {
                        mSwitch_sp.setChecked(true);
                    }
                }
            }
        });
        String barCode = getIntent().getStringExtra(GoodsCaptureActivity.class.getSimpleName());
        if (!TextUtils.isEmpty(barCode) && !barCode.equals("null")) {
            etBarcode.setText(barCode + "");
            etName.requestFocus();
        }

    }

    private void setListeners() {
        findViewById(R.id.save).setOnClickListener(this);
        findViewById(R.id.retreat).setOnClickListener(this);
        etExpirationDate.setOnClickListener(this);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                goodsCategory = (String) spinner.getSelectedItem();
                goodsCategory = keyData.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub

            }
        });
        pic_img.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                getPic();
            }
        });
        //tvAddPicHint.setOnClickListener(this);
    }


    private void showDatePicker() {
        Calendar mycalendar = Calendar.getInstance(Locale.getDefault());
        int year = mycalendar.get(Calendar.YEAR);
        int month = mycalendar.get(Calendar.MONTH);
        int day = mycalendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dpd = new DatePickerDialog(ScanAddGoods2Activity.this, datelistener, year, month, day);
        dpd.show();//显示DatePickerDialog组件
    }

    private DatePickerDialog.OnDateSetListener datelistener = new DatePickerDialog.OnDateSetListener() {
        /**params：view：该事件关联的组件
         * params：myyear：当前选择的年
         * params：monthOfYear：当前选择的月
         * params：dayOfMonth：当前选择的日
         */
        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
            //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
            //更新日期
            Calendar mycalendar = Calendar.getInstance();
            mycalendar.set(Calendar.YEAR, myyear);
            mycalendar.set(Calendar.MONTH, monthOfYear);
            mycalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            etExpirationDate.setText(Utils.getTime(mycalendar));
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.save:
                doCommit(v);
                break;
            case R.id.retreat:
                finish();
                break;
            case R.id.et_expiration_date:
                showDatePicker();
                break;
            default:
                break;
        }
    }

    public void doCommit(View view) {
        if (bitmapBean == null) {
            Toast.makeText(ScanAddGoods2Activity.this, "请添加商品图片！", Toast.LENGTH_SHORT).show();
            //postdata(null, false);
        } else {
              postdata(doc_id, false);
        }

    }

    private boolean postdata(String img, boolean ischeck) {
        String goodsName = etName.getText().toString().trim();
        if (TextUtils.isEmpty(goodsName)) {
            showToast(R.string.please_input_name);
            etName.requestFocus();
            return false;
        }
        String goodsBarcode = etBarcode.getText().toString().trim();
        if (TextUtils.isEmpty(goodsBarcode)) {
            showToast("请输入条码");
            etBarcode.requestFocus();
            return false;
        }


        String goodsSpec = etSpec.getText().toString().trim();
        if (TextUtils.isEmpty(goodsSpec)) {
            showToast("请输入规格");
            etSpec.requestFocus();
            return false;
        }

        String goodsStore = etStore.getText().toString().trim();
        if (TextUtils.isEmpty(goodsStore)) {
            showToast("请输入库存");
            etStore.requestFocus();
            return false;
        } else {
            //库存数量
            int goodsStoreNumber = 0;
            try {
                goodsStoreNumber = Integer.parseInt(goodsStore);
            } catch (Exception e) {

            }
            if (goodsStoreNumber <= 0) {
                showToast("库存必须大于0");
                etStore.requestFocus();
                return false;
            }

        }
        if (goodsStore.length() >= 9) {
            showToast("您输入的库存数量超上限");
            etStore.requestFocus();
            return false;
        }
        String goodsPrice = etPrice.getText().toString().trim();
        if (TextUtils.isEmpty(goodsPrice)) {
            showToast("请输入售价");
            etPrice.requestFocus();
            return false;
        } else {
            if (!MoneyUtil.moneyBigThan(goodsPrice, "0")) {
                showToast("售价需大于0");
                etPrice.requestFocus();
                return false;
            }
        }
        if (goodsPrice.length() >= 10) {
            showToast("您输入的售价超上限");
            etPrice.requestFocus();
            return false;
        }
        if (!TextUtils.isEmpty(etCost.getText().toString().trim())) {
            if (!MoneyUtil.moneyBigThan(etCost.getText().toString().trim(), "0")) {
                showToast("您输入的进货价需大于0");
                etCost.requestFocus();
                return false;
            }
        }
        if (etCost.getText().toString().length() >= 9) {
            showToast("您输入的进价超上限");
            etCost.requestFocus();
            return false;
        }
        if (etExpiration.getText().toString().length() >= 9) {
            showToast("您输入的保质期超上限");
            etExpiration.requestFocus();
            return false;
        }
        goodsPrice = MoneyUtil.formatMoney(goodsPrice);

        String goodsBrand = "自营";
        if (mSwitch_sp.isChecked()) {
            if (!isAddShopCheck()) {
                return false;
            }
        }
        if (mSwitch_coupon.isChecked()) {
            if (newbitmap == null) {
                Toast.makeText(getApplicationContext(), "商品如需支持礼券兑换,必须上传图片", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        String rebate = et_fanli.getText().toString().trim();
        if (TextUtils.isEmpty(rebate)) {
            rebate = "0";
        }

        if (!MoneyUtil.moneyComp(etPrice.getText().toString().trim(), rebate)) {

            Toast.makeText(getApplicationContext(), "返利价格不能大于售价", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (ischeck) {
            return true;
        }
//		String goodsVender = etVender.getText().toString().trim();
//		goodsVender = (TextUtils.isEmpty(goodsVender))? "0" : goodsVender;

        String goodsCost = etCost.getText().toString().trim();
        goodsCost = (TextUtils.isEmpty(goodsCost)) ? "0.00" : goodsCost;
        goodsCost = MoneyUtil.formatMoney(goodsCost);


        String goodsExpratdate = etExpirationDate.getText().toString().trim();
        goodsExpratdate = (TextUtils.isEmpty(goodsExpratdate)) ? "1900-01-01" : goodsExpratdate;


        String goodsExpiration = etExpiration.getText().toString().trim();
        goodsExpiration = (TextUtils.isEmpty(goodsExpiration)) ? "0" : goodsExpiration;

        String goodsIsshow = mSwitch.isChecked() ? "Y" : "N";
        String goodsIsshop = mSwitch_sp.isChecked() ? "Y" : "N";
        String goodsIsSupportCoupon = mSwitch_coupon.isChecked() ? "Y" : "N";


//        netRequest.requestAddGoods(1, rebate, bean.getItem_id(), bean.getItem_code(), goodsName, goodsCategory, goodsBrand, goodsBarcode, goodsIsshow, goodsIsshop, goodsIsSupportCoupon,
//                goodsCost, goodsPrice, goodsStore, goodsExpiration, goodsExpratdate, goodsSpec, img);
        showProgressDialog("添加商品", "提交中……");


        return true;
    }

    /**
     * 上传图片
     */
    private class uploadtask extends Thread {

        public void run() {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            newbitmap.compress(Bitmap.CompressFormat.PNG, 10, stream);
            InputStream in = new ByteArrayInputStream(stream.toByteArray());
            DefaultHttpClient httpclient = new DefaultHttpClient();
            try {
                HttpPost httppost = new HttpPost(Stores.http
                        + "/ops-storage/storage/upload");

                MultipartEntity reqEntity = new MultipartEntity();

                reqEntity.addPart("app_token", MainActivity.app_token);
                reqEntity.addPart("category", "oss_community");
                reqEntity.addPart("subffix", "jpg");
                reqEntity.addPart("up_load_file", "pic.jpg", in);
                httppost.setEntity(reqEntity);
                HttpResponse response = null;
                response = httpclient.execute(httppost);
                response.getStatusLine().toString();
                String strResult = EntityUtils.toString(response.getEntity());
                JSONObject obj = new JSONObject(strResult);

                String rsp_code = obj.getString("rsp_code");
                if (rsp_code.equals("succ")) {//图片上传成功


                    JSONObject data = obj.getJSONObject("data");
                    String doc_id = data.getString("doc_id");
                    Message msg = Message.obtain();
                    msg.what = MSG_IMG_SUCC;
                    msg.obj = doc_id;
                    mHandler.sendMessage(msg);
                    Log.v("mylog", "上传图片成功：" + doc_id);

                } else {
                    if (goToLogin.setGoToLogin(obj)) {

                    } else {
                        Message msg = Message.obtain();
                        msg.what = MSG_REQUEST_FAILED;
                        msg.obj = "图片上传失败";
                        mHandler.sendMessage(msg);
                    }
                }
                in.close();
                stream.close();

            } catch (Exception e) {
                Message msg = Message.obtain();
                msg.what = MSG_REQUEST_FAILED;
                msg.obj = "图片上传失败";
                mHandler.sendMessage(msg);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == FLAG_CHOOSE_IMG && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {

                    CropUtils.startCropActivity(uri, ScanAddGoods2Activity.this, 5, 5);
                }
            }
        } else if (requestCode == FLAG_CHOOSE_PHONE && resultCode == RESULT_OK) {

            File f = new File(SettingData.FILE_PIC_SCREENSHOT, localTempImageFileName);
            Uri uri = Uri.fromFile(f);
            if (uri != null) {
                UtilsBitmap.getCompressUri(uri);
                CropUtils.startCropActivity(uri, ScanAddGoods2Activity.this, 5, 5);
            }

        } else if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
            //剪切成功
            if (data != null) {
                final Uri resultUri = UCrop.getOutput(data);
                bitmapBean = UtilsBitmap.addFilePath3(resultUri.getPath(), this);
                if (bitmapBean.getIsBm()!=null){

                    netRequest.requestUploadPic(4, bitmapBean.getIsBm());
                }
//                newbitmap = vistabitmap;
//                pic_img.setImageBitmap(vistabitmap);
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            //剪切失败
            Toast.makeText(ScanAddGoods2Activity.this, "图片剪切失败！", Toast.LENGTH_SHORT)
                    .show();
        }

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 0) {

            } else if (requestCode == 1) {

            }
        }
    }


    /*拍照的照片存储位置*/
    private static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera");
    private File mPhotoFile;//照相机拍照得到的图片

    protected void doTakePhoto() {
        if (!PHOTO_DIR.exists()) {
            boolean isMade = PHOTO_DIR.mkdirs();
            if (isMade) {
                mPhotoFile = new File(PHOTO_DIR, Utils.getPhotoFileName());// 给新照的照片文件命名
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));
                startActivityForResult(intent, 0);
            }
        }
    }


    protected void doPickPhotoFromGallery() {
        final Intent intent = getPhotoPickIntent();
        startActivityForResult(intent, 1);
    }

    public static Intent getPhotoPickIntent() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        intent.setType("image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 9);
        intent.putExtra("aspectY", 16);
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 180);
        intent.putExtra("return-data", true);
        return intent;
    }

    public void getPic() {
        new AlertDialog.Builder(ScanAddGoods2Activity.this)
                .setTitle("请选择图片来源")
                .setItems(new String[]{"相册", "相机"},
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                if (which == 0) {
                                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    startActivityForResult(intent,
                                            FLAG_CHOOSE_IMG);
                                } else if (which == 1) {
                                    String status = Environment
                                            .getExternalStorageState();
                                    if (status
                                            .equals(Environment.MEDIA_MOUNTED)) {
                                        try {
                                            localTempImageFileName = "";
                                            localTempImageFileName = String
                                                    .valueOf((new Date())
                                                            .getTime())
                                                    + ".png";
                                            File filePath = SettingData.FILE_PIC_SCREENSHOT;
                                            if (!filePath.exists()) {
                                                filePath.mkdirs();
                                            }
                                            Intent intent = new Intent(
                                                    MediaStore.ACTION_IMAGE_CAPTURE);
                                            File f = new File(filePath,
                                                    localTempImageFileName);
                                            // localTempImgDir和localTempImageFileName是自己定义的名字
                                            Uri u = Uri.fromFile(f);
                                            intent.putExtra(
                                                    MediaStore.Images.Media.ORIENTATION,
                                                    0);
                                            intent.putExtra(
                                                    MediaStore.EXTRA_OUTPUT,
                                                    u);
                                            startActivityForResult(
                                                    intent,
                                                    FLAG_CHOOSE_PHONE);
                                        } catch (ActivityNotFoundException e) {
                                            //
                                        }
                                    }
                                }

                            }
                        }).show();
    }

    public boolean isAddShopCheck() {
        try {
            String s_name = etName.getText().toString();
            if (TextUtils.isEmpty(s_name)) {
                Toast.makeText(ScanAddGoods2Activity.this, "添加到网店需要添加商品名", Toast.LENGTH_SHORT).show();
                return false;
            }

            String s_barcode = etBarcode.getText().toString();
            if (TextUtils.isEmpty(s_barcode)) {
                Toast.makeText(ScanAddGoods2Activity.this, "添加到网店需要添加条码", Toast.LENGTH_SHORT).show();
                return false;
            }

            String s_spec = etSpec.getText().toString();
            if (TextUtils.isEmpty(s_spec)) {
                Toast.makeText(ScanAddGoods2Activity.this, "添加到网店需要添加商品规格", Toast.LENGTH_SHORT).show();
                return false;
            }


            String s_store = etStore.getText().toString();
            if (TextUtils.isEmpty(s_store)) {
                Toast.makeText(ScanAddGoods2Activity.this, "添加到网店需要添加库存", Toast.LENGTH_SHORT).show();
                return false;
            } else {
                if (Integer.parseInt(s_store) <= 0) {
                    Toast.makeText(ScanAddGoods2Activity.this, "添加到网店库存需大于0", Toast.LENGTH_SHORT).show();
                    return false;
                }
            }

            String s_price = etPrice.getText().toString();
            if (TextUtils.isEmpty(s_price)) {
                Toast.makeText(ScanAddGoods2Activity.this, "添加到网店需要添加售价", Toast.LENGTH_SHORT).show();
                return false;
            } else {
                if (Double.parseDouble(s_price) <= 0) {
                    Toast.makeText(ScanAddGoods2Activity.this, "添加到网店售价需大于0", Toast.LENGTH_SHORT).show();
                    return false;
                }
            }


            String s_cost = etCost.getText().toString();
            if (TextUtils.isEmpty(s_cost)) {
                Toast.makeText(ScanAddGoods2Activity.this, "添加到网店需要添加进价", Toast.LENGTH_SHORT).show();
                return false;
            } else {
                if (Double.parseDouble(s_cost) <= 0) {
                    Toast.makeText(ScanAddGoods2Activity.this, "添加到网店进价需大于0", Toast.LENGTH_SHORT).show();
                    return false;
                }
            }


            if (newbitmap == null) {
                Toast.makeText(ScanAddGoods2Activity.this, "添加到网上便利店需要上传商品图片", Toast.LENGTH_SHORT).show();
                return false;
            }

        } catch (Exception e) {

        }
        return true;
    }

}
